package com.sanq.product.books.controller;

import com.sanq.product.books.entity.vo.JobsVo;
import com.sanq.product.books.service.JobsService;
import com.sanq.product.books.utils.JobManage;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.date.LocalDateUtils;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.LogUtil;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/jobs")
public class JobsController {

    @Resource
    private JobsService jobsService;
    @Resource
    private Scheduler scheduler;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    private void startJob(JobsVo jobsVo) {
        taskExecutor.execute(() -> {
            try {
                JobManage.startJob(scheduler, jobsVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void stopJob(Long id) {
        taskExecutor.execute(() -> {
            try {
                JobManage.stopJob(scheduler, id);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        });
    }

    @LogAnnotation(description = "通过ID获取详情-定时任务列表")
    @GetMapping(value = "/get/{id}")
    public Response getById(HttpServletRequest request, @PathVariable("id") Long id) {

        JobsVo jobsVo = jobsService.findById(id);

        return jobsVo != null ? new Response().success(jobsVo) : new Response().failure();
    }

    @LogAnnotation(description = "删除数据-定时任务列表")
    @DeleteMapping(value = "/delete")
    public Response deleteById(HttpServletRequest request, @RequestBody JobsVo jobsVo) {

        int result = jobsService.delete(jobsVo);

        if (result != 0) {
            stopJob(jobsVo.getId());
        }

        return result != 0 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "列表展示-定时任务列表")
    @GetMapping(value = "/list")
    public Response findListByPager(HttpServletRequest request, JobsVo jobsVo, Pagination pagination) {

        Pager<JobsVo> pager = jobsService.findListByPage(jobsVo, pagination);

        return new Response().success(pager);
    }

    @LogAnnotation(description = "全部数据-定时任务列表")
    @GetMapping(value = "/all")
    public Response findList(HttpServletRequest request, JobsVo jobsVo) {

        List<JobsVo> list = jobsService.findList(jobsVo);

        return list != null ? new Response().success(list) : new Response().failure();
    }

    @LogAnnotation(description = "保存-定时任务列表")
    @PostMapping(value = "/save")
    public Response add(HttpServletRequest request, @RequestBody @Valid JobsVo jobsVo) {

        jobsVo.setId(System.currentTimeMillis());
        int result = jobsService.save(jobsVo);

        if (result != 0) {
            if (jobsVo.getIsEnable() == 1) {
                startJob(jobsVo);
            }
        }
        return result != 0 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "修改-定时任务列表")
    @PutMapping(value = "/update/{id}")
    public Response updateByKey(HttpServletRequest request, @RequestBody @Valid JobsVo jobsVo, @PathVariable("id") Long id) {

        int result = jobsService.update(jobsVo, id);

        if (result != 0) {
            JobsVo oldJobsVo = jobsService.findById(id);

            if (oldJobsVo.getIsEnable() == 1) {
                startJob(oldJobsVo);
            } else stopJob(id);
        }


        return result != 0 ? new Response().success() : new Response().failure();
    }
}